package com.winning.sx.microframework.controller.sysmanage;

import com.alibaba.fastjson.JSON;
import com.winning.dapi.data.entity.DataTable;
import com.winning.sx.microframework.common.util.Constains;
import com.winning.sx.microframework.dao.sysmanage.ModelManageDao;
import com.winning.sx.microframework.model.exception.CustomException;
import com.winning.sx.microframework.model.manage.LoginSession;
import com.winning.sx.microframework.model.manage.ModelManageModel;
import com.winning.sx.microframework.plugins.wx.WxConfig;
import com.winning.sx.microframework.service.EasyService;
import com.winning.sx.microframework.service.sysmanage.ConstService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xiaoY on 2016/9/12.
 */
@Controller
public class IndexController {
    @Autowired
    public ModelManageDao modelManageDao;
    @Autowired
    private EasyService easyService;
    @Autowired
    ConstService service;
    @Value("${system.style}")
    private String systemStyle;

    @RequestMapping(value = {"", "/", "/index", "/userMain", "/doctorMain"})
    public ModelAndView indexPage(String param) throws IOException {
//        String systemStyle = BaseUtil.getPropValue("system.style");
        LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
        ModelAndView mv = new ModelAndView();
        if (login == null) {
            mv = new ModelAndView("login");
            mv.addObject("appId", WxConfig.appid);
            return mv;
        }
        //临时这么写吧，应该写到登录端比较合适，但是考虑到加载
        if ("userMain".equals(login.getIndexUrl())) {
            mv = new ModelAndView("userMain");
        } else if ("doctorMain".equals(login.getIndexUrl())) {
            mv = new ModelAndView("doctorMain");
        } else {
            String viewName = "indexTop";
            if (systemStyle.equals("tab"))
                viewName = "indexTab";
            Subject subject = SecurityUtils.getSubject();
            String userName = ((LoginSession) subject.getSession().getAttribute("loginSession")).getcUserName();
            mv = new ModelAndView(viewName);
            mv.addObject("viewName", viewName);
            mv.addObject("userName", userName);
            if (SecurityUtils.getSubject().isAuthenticated()) {
                Session session = subject.getSession();
                String systemid = ((LoginSession) session.getAttribute("loginSession")).getcSystemID();
                List<ModelManageModel> menus = null;
                try {
                    menus = modelManageDao.queryModelsBySystemID(systemid);
                } catch (CustomException e) {
                    e.printStackTrace();
                }
                mv.addObject("userMenus", menus);
            }
        }

        return mv;
    }


    @RequestMapping(value = {"/main"})
    public ModelAndView areaPage() throws Exception {
        LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
        ModelAndView mv = new ModelAndView(login.getIndexUrl());
        Map<String, String> param = new HashMap();
        param.put("organizationType", "400001");
        param.put("superOrganizationId", login.getOrgId());
        mv.addObject("organizationName", JSON.toJSON(service.queryMyOrg(param)).toString());

        param.put("warehouseFlag", "401001");
        mv.addObject("organizationNameForWarehouse", JSON.toJSON(service.queryMyOrg(param)).toString());

        List secrecy = service.queryCount("116");
        mv.addObject("secrecy", secrecy);
        return mv;
    }

    @RequestMapping(value = {"/warehouseList"})
    public ModelAndView warehouseList() throws Exception {
        LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
        ModelAndView mv = new ModelAndView("/user/warehouse/list");
        Map<String, String> param = new HashMap();
        param.put("organizationType", "400001");
        param.put("superOrganizationId", login.getOrgId());
        param.put("warehouseFlag", "401001");
        mv.addObject("organizationName", JSON.toJSON(service.queryMyOrg(param)).toString());
        return mv;
    }

    @RequestMapping(value = {"/equipmentSearch"})
    public ModelAndView equipmentSearch() throws Exception {
        ModelAndView mv = new ModelAndView("/user/equipment/search");
        List secrecy = service.queryCount("116");
        mv.addObject("secrecy", secrecy);
        List state = service.queryCount("203");
        mv.addObject("state", state);
        return mv;
    }

    @RequestMapping(value = {"/search"})
    public ModelAndView search() throws Exception {
        ModelAndView mv = new ModelAndView("/user/search");
        List secrecy = service.queryCount("116");
        mv.addObject("secrecy", secrecy);
        List state = service.queryCount("203");
        mv.addObject("state", state);
        LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
        Map<String, String> param = new HashMap();
        param.put("organizationType", "400001");
        param.put("superOrganizationId", login.getOrgId());
        mv.addObject("organizationName", JSON.toJSON(service.queryMyOrg(param)).toString());
        return mv;
    }

    @RequestMapping(value = {"/alllist"})
    public ModelAndView alllist() throws Exception {
        ModelAndView mv = new ModelAndView("/user/alllist");
        List secrecy = service.queryCount("116");
        mv.addObject("secrecy", secrecy);
        List state = service.queryCount("203");
        mv.addObject("state", state);
        return mv;
    }

    @RequestMapping(value = {"/myMain"})
    public ModelAndView myMain() throws Exception {
        ModelAndView mv = new ModelAndView("/user/equipment/myMain");
        return mv;
    }

    @RequestMapping(value = {"/myCheck"})
    public ModelAndView myCheck() throws Exception {
        ModelAndView mv = new ModelAndView("/user/equipment/myCheck");
        return mv;
    }

    @RequestMapping(value = {"/myJob"})
    public ModelAndView myJob() throws Exception {
        ModelAndView mv = new ModelAndView("/user/equipment/myJob");
        return mv;
    }

    @RequestMapping(value = {"/changeIn"})
    public ModelAndView changeIn() throws Exception {
        ModelAndView mv = new ModelAndView("/user/warehouse/changeIn");
        LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
        Map<String, String> param = new HashMap();
        param.put("organizationType", "400001");
        param.put("superOrganizationId", login.getOrgId());
        param.put("warehouseFlag", "401001");
        mv.addObject("organizationName", JSON.toJSON(service.queryMyOrg(param)).toString());
        return mv;
    }

    @RequestMapping(value = {"/changeOut"})
    public ModelAndView changeOut() throws Exception {
        LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
        ModelAndView mv = new ModelAndView("/user/warehouse/changeOut");
        Map<String, String> param = new HashMap();
        param.put("organizationType", "400001");
        param.put("superOrganizationId", login.getOrgId());
        param.put("warehouseFlag", "401001");
        mv.addObject("organizationName", JSON.toJSON(service.queryMyOrg(param)).toString());
        return mv;
    }

    @RequestMapping(value = {"/changeMove"})
    public ModelAndView changeMove() throws Exception {
        LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
        ModelAndView mv = new ModelAndView("/user/warehouse/changeMove");
        Map<String, String> param = new HashMap();
        param.put("organizationType", "400001");
        param.put("superOrganizationId", login.getOrgId());
        param.put("warehouseFlag", "401001");
        mv.addObject("organizationName", JSON.toJSON(service.queryMyOrg(param)).toString());
        return mv;
    }

    @RequestMapping(value = {"/elist"})
    public ModelAndView elist() throws Exception {
        ModelAndView mv = new ModelAndView("/user/elist");
        return mv;
    }

    @RequestMapping(value = {"/plist"})
    public ModelAndView plist() throws Exception {
        ModelAndView mv = new ModelAndView("/user/plist");
        List type = service.queryCount("301");
        mv.addObject("type", type);
        return mv;
    }

    @RequestMapping(value = {"/warehouseReport"})
    public ModelAndView warehouseReport() throws Exception {
        LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
        ModelAndView mv = new ModelAndView("/user/warehouse/report");
        List eqClass = easyService.querySql("select * from BASE_EqClass where superId=0 and validFlag='100001'", new HashMap()).getDataRows();
        mv.addObject("eqClass", eqClass);
        return mv;
    }

    @RequestMapping(value = {"/pdetail/{flowCode}"})
    public ModelAndView pdetail(@PathVariable("flowCode") String flowCode) throws Exception {
        ModelAndView mv = new ModelAndView("/user/pdetail");
        String sql = "select c1.name typeName,c2.name brandName,p.* from BASE_Product p " +
                "left join BASE_Const c1 on c1.code=p.typeCode " +
                "left join BASE_Const c2 on c2.code=p.brandCode " +
                "where  p.code=:flowCode and  p.validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "'"
                + " and p.productState='" + Constains.PRODUCT_SHOW_TRUE + "'";
        Map param = new HashMap();
        param.put("flowCode", flowCode);
        mv.addObject("data", easyService.querySql(sql, param).getDataRows().get(0));
        return mv;
    }

    @RequestMapping(value = {"/eresult/{flowCode}"})
    public ModelAndView eresult(@PathVariable("flowCode") String flowCode) throws Exception {
        ModelAndView mv = new ModelAndView("/user/eresult");
        String sql = "select o.name orgName, " +
                "e.usePosition, e.name name, m.id, m.flowCode , e.id eid, " +
                "c1.name questionTypeName,m.questionDescripe,m.createTime,m.updateTime,m.telephone , " +
                "m.maintenanceResult, m.maintenanceDescribe, " +
                "c2.name maintenanceResultName,m.maintenanceTime " +
                " from BUSI_MaintenanceApplication m " +
                "left join BASE_Const c1 on c1.code=m.questionTypeCode " +
                "left join BASE_Equipment e on e.id=m.equipmentId " +
                " left join BASE_Organization o on e.organizationId =o.id " +
                " left join BASE_Const c2 on m.maintenanceResult=c2.code where m.flowCode=:flowCode and m.validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "' and m.state='" + Constains.STATE_REPAIR_YES + "'";
        Map param = new HashMap();
        param.put("flowCode", flowCode);
        mv.addObject("maintenance", easyService.querySql(sql, param).getDataRows().get(0));

        //维修方式
        List type = service.queryCount("900");
        mv.addObject("repairType", type);
        //失败类型
        List brand = service.queryCount("901");
        mv.addObject("failReason", brand);

        return mv;
    }

    @RequestMapping(value = {"/ecomment/{flowCode}"})
    public ModelAndView ecomment(@PathVariable("flowCode") String flowCode) throws Exception {
        ModelAndView mv = new ModelAndView("/user/ecomment");
        String sql = "select case when op.id is null then o.name else op.name+'-'+o.name end orgName, " +
                "e.usePosition, e.name name, m.id, m.flowCode ,e.id eid,  " +
                "c1.name questionTypeName,m.questionDescripe,m.createTime,m.updateTime,m.telephone , " +
                "m.maintenanceResult, m.maintenanceDescribe, " +
                "c2.name maintenanceResultName,m.maintenanceTime " +
                " from BUSI_MaintenanceApplication m " +
                "left join BASE_Const c1 on c1.code=m.questionTypeCode " +
                "left join BASE_Equipment e on e.id=m.equipmentId " +
                " left join BASE_Organization o on e.organizationId =o.id full join BASE_Organization op on o.superOrganizationId=op.id " +
                " left join BASE_Const c2 on m.maintenanceResult=c2.code where m.flowCode=:flowCode and m.validFlag='" + Constains.SYS_VALIDFLAG_TRUE + "' and m.state='" + Constains.STATE_REPAIR_FINISH + "'";
        Map param = new HashMap();
        param.put("flowCode", flowCode);
        mv.addObject("maintenance", easyService.querySql(sql, param).getDataRows().get(0));
        return mv;
    }

    @RequestMapping(value = {"/edetail/{QRcode}"}, method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView edetail(@PathVariable("QRcode") String QRcode) throws Exception {
        ModelAndView mv = new ModelAndView("/user/edetail");
        //品牌， 型号，问题类型

        DataTable eqRootClassS = easyService.querySql("select e2.name+'-'+e.name name,e.id,e.code from BASE_EqClass e left join BASE_EqClass e2 on e.superId=e2.id where e.superId!=0 and e.validFlag='100001' and e.type='301001'", new HashMap());
        List eqRootClass = eqRootClassS.getDataRows();
        mv.addObject("type", eqRootClass);

//        List type = service.queryCount("301");
//        mv.addObject("type", type);
        List brand = service.queryCount("300");
        mv.addObject("brand", brand);
        List question = service.queryCount("110");
        mv.addObject("question", question);
        List secrecy = service.queryCount("116");
        mv.addObject("secrecy", secrecy);
        mv.addObject("QRcode", QRcode);

        List useType = service.queryCount("108");
        mv.addObject("useType", useType);
        return mv;
    }

    @RequestMapping(value = {"/userInfo"}, method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView userInfo() throws Exception {
        ModelAndView mv = new ModelAndView("/user/userInfo");
        LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
        if (login == null) {
            mv = new ModelAndView("login");
            mv.addObject("appId", WxConfig.appid);
            return mv;
        }
        List list= easyService.querySql("select op.name+' ' +o.name orgName,r.cRoleName roleName,c.name typeName,w2.name wxName,w2.headPhoto, " +
                        " s.organizationId, s.name,s.telephone,s.telephone2,s.telephone3,s.telephone4,s.birthday,s.roomNo " +
                        "from BASE_Staff s " +
                        "left join BASE_Organization o on s.organizationId=o.id " +
                        "left join BASE_Organization op on o.superOrganizationId=op.id " +
                        "left join PM_ROLES r on s.role=r.cRoleID  left join PM_StaffWeChat w on w.staffId=s.id and w.validFlag='100001'" +
                        " left join PM_StaffWeChat w2 on w2.openId=w.openId and w2.name != 'null' " +
                        "left join BASE_Const c on s.staffType=c.code where   s.id=" + login.getStaffId() +
                        ((login.getcUserOpenId() != null && !"".equals(login.getcUserOpenId()) && !"null".equals(login.getcUserOpenId())) ? " and w.openId='" + login.getcUserOpenId() + "'" : "")
                , new HashMap<>()).getDataRows();
        if(list.size()==0){
            mv = new ModelAndView("login");
            mv.addObject("appId", WxConfig.appid);
            mv.addObject("state","9");
            return mv;
        }
        Map userInfo = (Map)list.get(0);
        mv.addObject("userInfo", userInfo);

        List type = service.queryCount("311");
        mv.addObject("type", type);

        Map<String, String> param = new HashMap();
        param.put("organizationType", "400001");
        param.put("superOrganizationId", "0");
        mv.addObject("organizationName", JSON.toJSON(service.queryMyOrg(param)).toString());
        return mv;
    }
}
